﻿using System.Threading.Tasks;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Infrastructure;
using System.Collections.Generic;
using Bordspil.Models;
using System.Linq;
using System;

namespace Bordspil.Controllers
{
    public class TicTacToeHub : Hub
    {
       
        IAppRepository m_db = new AppRepository();

        public void Join(string groupId, string userName)
        {
            int id;
            id = Int32.Parse(groupId); //nota frekar TryParse

            PlayerList p = new PlayerList();
            p.PlayerName = userName;
            p.id = id;
            p.IsItMyTurn = false;
            m_db.AddToPlayerList(p);
            m_db.Save();

            Groups.Add(Context.ConnectionId, groupId);
            
        }

        public void ClickCell(string groupName, string cellId) //groupName == instanceId (id)
        {

            Clients.OthersInGroup(groupName).cellClicked(cellId);
        }

        public void StartGame(string groupName)
        {
            var id2 = Convert.ToInt32(groupName);
            var result = (from r in m_db.GetPlayerList()
                          where r.id == id2
                          select r);
            var counter = result.Count();
            if (result.Count() == 2)
            {
                //leikur ma byrja og sa sem byrjar er sa sem stofnar leikinn
                var starter = result.FirstOrDefault().PlayerName;

                Clients.Group(groupName).startGame("start", starter);
                
            }
            else
            {
                Clients.Group(groupName).startGame("Bid eftir motspilara");
            }
        }

        public void WhosTurnIsIt(string groupName, string userName)
        {
            int id = Int32.Parse(groupName);
            var result = (from u in m_db.GetPlayerList()
                          where u.id == id && u.PlayerName == userName
                          select u).SingleOrDefault();

            //skilar notendanafni a naesta sem ma gera
            if (result == null)
            {
                return;
            }

            Clients.OthersInGroup(groupName).whosTurnIsIt(userName);
            
        }

    }
}